package datastructure.find;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author MaoLin Wang
 * @description TODO
 * @date 2020/8/26 12:38 下午
 */
public class SequentialSearchST<Key,Value>{
    private  Node first;
    private  int size;

    public class Node{
        private  Key key;
        private  Value value;
        private  Node next;

        public Node(Key key, Value value,Node next) {
            this.key = key;
            this.value = value;
            this.next=next;
        }
    }

    public SequentialSearchST() {
    }

    public Value get(Key key){
        if (size==0){
            return null;
        }
        for (Node temp=first;temp!=null; temp= temp.next){
            if (temp.key.equals(key)){
                return temp.value;
            }
        }
        return null;
    }

    public void put(Key key,Value value){
        if (key==null || value==null){
            return;
        }
        for (Node temp=first;temp!=null;temp=temp.next){
            if (temp.key.equals(key)){
                temp.value=value;
                return;
            }
        }
        first=new Node(key,value,first);
        size++;
    }

    public void delete(Key key){
        if (key==null){
            return;
        }
        if (first.key.equals(key)){
            first=first.next;
            size--;
            return;
        }
        Node temp=first;
        Node next=first.next;
        while (next!=null){
            if (next.key.equals(key)){
                temp.next=next.next;
                size--;
                break;
            }
            temp=temp.next;
            next=next.next;
        }
    }

    public Iterable<Key> keys(){
        Queue<Key>queue=new LinkedList<>();
        Node temp=first;
        while (temp!=null){
            queue.add(temp.key);
            temp=temp.next;
        }
        return queue;
    }
    public static void main(String[] args) {
        SequentialSearchST<String , String> st = new SequentialSearchST<>();
        st.put("1","wml");
        st.put("3","wml3");
        st.put("5","wml5");
        st.put("4","wml4");
        st.put("10","wml0");
        st.put("17","wml7");

        System.out.println(st.get("1"));
        System.out.println(st.get("5"));
        System.out.println(st.get("10"));
        System.out.println(st.get("17"));

        st.delete("3");
        System.out.println(st.get("3"));
    }

}
